package top.atcra.rpc.serialization.impl;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import top.atcra.rpc.serialization.Serializer;

/**
 * @author atcra
 * @date 2025-3-28
 */
@Slf4j
public class JsonSerializer implements Serializer {
    @Override
    public byte[] serialize(Object object) {
        if (object == null) {
            return null;
        }

        byte[] result = JSON.toJSONBytes(object);
        if (log.isDebugEnabled()) {
            log.debug("使用JSON方式序列化对象【{}】成功，编码后二进制长度为{}", object, result.length);
        }
        return result;

    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        if (bytes == null || clazz == null) {
            return null;
        }
        T t = JSON.parseObject(bytes, clazz);
        if (log.isDebugEnabled()) {
            log.debug("使用JSON方式反序列化对象【{}】成功", clazz);
        }
        return t;
    }


}
